package cn.eva.service.Impl.admin;

import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import cn.eva.common.LayuiTableResult;
import cn.eva.common.ResultJosn;
import cn.eva.dao.EvaWhatTimeMapper;
import cn.eva.entity.AddJobInfo;
import cn.eva.entity.EvaWhatTime;
import cn.eva.example.EvaWhatTimeExample;
import cn.eva.job.impl.StatisticalFractionJob;
import cn.eva.service.admin.SysEvaluatingManageService;
import cn.eva.service.job.JobService;

@Service
public class SysEvaluatingManageServiceImpl implements SysEvaluatingManageService {
	@Autowired
	private EvaWhatTimeMapper evaWhatTimeMapper; // 评测任务mapper
	@Autowired
	private JobService jobService;

	/**
	 * 添加评测任务
	 */
	@Override
	@Transactional
	public ResultJosn add(EvaWhatTime evaWhatTime) {

		if (StringUtils.isBlank(evaWhatTime.getWtNumber())) {
			throw new IllegalArgumentException("批次编号错误");
		}
		if (evaWhatTime.getWtState() == true) {
			// 验证评测任务状态在数据库中是否有开启的
			EvaWhatTimeExample whatTimeExample = new EvaWhatTimeExample();
			whatTimeExample.createCriteria().andWtStateEqualTo(true);
			List<EvaWhatTime> list = evaWhatTimeMapper.selectByExample(whatTimeExample);
			if (list != null && !list.isEmpty() || list.size() != 0) {
				return new ResultJosn(HttpStatus.BAD_REQUEST.value(), HttpStatus.BAD_REQUEST.getReasonPhrase(),
						"添加失败，系统中已经存在一次开启任务");
			}
		}
		EvaWhatTime check = this.checkEvaManage(evaWhatTime.getWtNumber());
		if (null != check && (check.getWtNumber()).equals(evaWhatTime.getWtNumber())) {
			throw new IllegalArgumentException("评测任务已经存在已存在！请重新修改批次编号");
		}
		evaWhatTimeMapper.insert(evaWhatTime);

		//启动任务
		AddJobInfo addJobInfo = new AddJobInfo(evaWhatTime.getWtDescribe(), evaWhatTime.getWtNumber(),
				evaWhatTime.getWtEnd());
		try {
			jobService.addUp(addJobInfo);
		} catch (Exception e) {
			e.printStackTrace();
			throw new IllegalArgumentException("任务启动失败");
		}
		return new ResultJosn(HttpStatus.OK.value(), HttpStatus.OK.getReasonPhrase(), "添加成功");
	}

	/**
	 * 删除评测任务
	 */
	@Override
	@Transactional
	public ResultJosn delete(String wtid) {
		// 删除时验证是否启动

		EvaWhatTime evaWhatTime = this.checkEvaManageByState(wtid);
		if (evaWhatTime.getWtState()) {
			throw new IllegalArgumentException("删除评测任务列存在启动中，禁止删除");
		}

		//按条件删除数据
		evaWhatTimeMapper.deleteByPrimaryKey(wtid);
		//启动任务
		AddJobInfo addJobInfo = new AddJobInfo(evaWhatTime.getWtDescribe(), evaWhatTime.getWtNumber(),
				evaWhatTime.getWtEnd());
		try {
			jobService.delUp(addJobInfo);
		} catch (Exception e) {
			e.printStackTrace();
			throw new IllegalArgumentException("任务启动失败");
		}
		return new ResultJosn(HttpStatus.OK.value(), HttpStatus.OK.getReasonPhrase(), "删除成功");
	}

	/**
	 * 修改评测任务
	 */
	@Override
	@Transactional
	public ResultJosn update(EvaWhatTime evaWhatTime) {
		if (StringUtils.isBlank(evaWhatTime.getWtId())) {
			throw new IllegalArgumentException("wtid错误！");
		}
		EvaWhatTime check = this.checkEvaManage(evaWhatTime.getWtNumber());
		if (null != check && (check.getWtNumber()).equals(evaWhatTime.getWtNumber())
				&& !(check.getWtId()).equals(evaWhatTime.getWtId())) {
			throw new IllegalArgumentException("评测任务已经存在已存在！请重新修改编号");
		}
		// 默认状态为false
		evaWhatTime.setWtState(null);
		evaWhatTimeMapper.updateByPrimaryKeySelective(evaWhatTime);
		//启动任务
		AddJobInfo addJobInfo = new AddJobInfo(evaWhatTime.getWtDescribe(), evaWhatTime.getWtNumber(),
				evaWhatTime.getWtEnd());
		try {
			jobService.updUp(addJobInfo);
		} catch (Exception e) {
			e.printStackTrace();
			throw new IllegalArgumentException("任务启动失败");
		}
		return new ResultJosn(HttpStatus.OK.value(), HttpStatus.OK.getReasonPhrase(), "修改成功");
	}

	/**
	 * 修改评测任务状态
	 */
	@Override
	@Transactional
	public ResultJosn updateState(EvaWhatTime evaWhatTime) {
		if (evaWhatTime.getWtState() == true) {
			// 验证评测任务状态在数据库中是否有开启的
			EvaWhatTimeExample whatTimeExample = new EvaWhatTimeExample();
			whatTimeExample.createCriteria().andWtStateEqualTo(true);
			List<EvaWhatTime> list = evaWhatTimeMapper.selectByExample(whatTimeExample);
			if (list != null && !list.isEmpty() || list.size() != 0) {
				return new ResultJosn(HttpStatus.BAD_REQUEST.value(), HttpStatus.BAD_REQUEST.getReasonPhrase(),
						"开启失败，系统中已经存在一次任务");
			}
		}
		// 根据主键修改
		evaWhatTimeMapper.updateByPrimaryKeySelective(evaWhatTime);
		EvaWhatTime evaWhatTime2 = evaWhatTimeMapper.selectByPrimaryKey(evaWhatTime.getWtId());
		if (evaWhatTime2.getWtState()) {
			//启动任务
			AddJobInfo addJobInfo = new AddJobInfo(evaWhatTime2.getWtDescribe(), evaWhatTime2.getWtNumber(),
					evaWhatTime2.getWtEnd());

			if (addJobInfo.getDeadline().getTime() < (new Date()).getTime()) {
				throw new IllegalArgumentException("任务结束时间已过，创建失败");
			}
			try {
				jobService.resumejob(addJobInfo);
			} catch (Exception e) {
				e.printStackTrace();
				throw new IllegalArgumentException("任务启动失败");
			}
		} else {
			//启动任务
			AddJobInfo addJobInfo = new AddJobInfo(evaWhatTime.getWtDescribe(), evaWhatTime.getWtNumber(),
					evaWhatTime.getWtEnd());
			try {
				jobService.pause(addJobInfo);
			} catch (Exception e) {
				e.printStackTrace();
				throw new IllegalArgumentException("任务启动失败");
			}
		}

		return new ResultJosn(HttpStatus.OK.value(), HttpStatus.OK.getReasonPhrase(), "修改成功");
	}

	/**
	 * 查询所有评测任务
	 * 
	 * @param evaWhatTime
	 * @param page
	 * @param pageSize
	 * @return
	 */
	@Override
	public LayuiTableResult select(EvaWhatTime evaWhatTime, Integer page, Integer pageSize) {
		LayuiTableResult resultJosn = new LayuiTableResult();
		// 构造条件
		EvaWhatTimeExample example = new EvaWhatTimeExample();
		example.setOrderByClause("wt_number DESC");

		// 开启分页查找
		PageHelper.startPage(page, pageSize);
		List<EvaWhatTime> list = evaWhatTimeMapper.selectByExample(example);
		PageInfo<EvaWhatTime> pageInfo = new PageInfo<>(list, pageSize);
		resultJosn.setCode(HttpStatus.OK.value());
		resultJosn.setMessage(HttpStatus.OK.getReasonPhrase());
		resultJosn.setCount(pageInfo.getTotal());
		resultJosn.setData(pageInfo.getList());
		return resultJosn;
	}

	/**
	 * 查询一次评测任务
	 */
	@Override
	public ResultJosn selectBytId(String wtid) {
		if (StringUtils.isBlank(wtid)) {
			throw new IllegalArgumentException("wtid 错误！");
		}
		EvaWhatTimeExample whatTimeExample = new EvaWhatTimeExample();
		whatTimeExample.createCriteria().andWtIdEqualTo(wtid);
		List<EvaWhatTime> ewtime = evaWhatTimeMapper.selectByExample(whatTimeExample);
		return new ResultJosn(HttpStatus.OK.value(), HttpStatus.OK.getReasonPhrase(), ewtime.get(0));
	}

	/**
	 * 根据评测编号查找是否重复
	 * 
	 * @return
	 */
	public EvaWhatTime checkEvaManage(String wnumber) {
		EvaWhatTimeExample whatTimeExample = new EvaWhatTimeExample();
		whatTimeExample.createCriteria().andWtNumberEqualTo(wnumber);
		List<EvaWhatTime> list = evaWhatTimeMapper.selectByExample(whatTimeExample);
		if (CollectionUtils.isEmpty(list)) {
			return null;
		}
		return (EvaWhatTime) list.get(0);
	}

	/**
	 * 根据wtid 查询状态
	 * @param wtId
	 * @return
	 */
	public EvaWhatTime checkEvaManageByState(String wtId) {
		EvaWhatTimeExample whatTimeExample = new EvaWhatTimeExample();
		whatTimeExample.createCriteria().andWtIdEqualTo(wtId);
		List<EvaWhatTime> list = evaWhatTimeMapper.selectByExample(whatTimeExample);
		if (CollectionUtils.isEmpty(list)) {
			return null;
		}
		return (EvaWhatTime) list.get(0);
	}

	/**
	 * 
	 * <p>Title: pauseAll</p>   
	 * <p>Description: 关闭所有状态为暂停</p>   
	 * @param evaWhatTime   
	 * @see cn.eva.service.admin.SysEvaluatingManageService#pauseAll(cn.eva.entity.EvaWhatTime)
	 */
	@Override
	@Transactional
	public void pauseAll(EvaWhatTime evaWhatTime) {
		evaWhatTime.setWtState(false);
		EvaWhatTimeExample example = new EvaWhatTimeExample();
		example.createCriteria().andWtIdLike("%" + StatisticalFractionJob.class.getName())
				.andWtNumberEqualTo(evaWhatTime.getWtNumber());
		evaWhatTimeMapper.updateByExampleSelective(evaWhatTime, example);
		//暂停任务
		AddJobInfo addJobInfo = new AddJobInfo(evaWhatTime.getWtDescribe(), evaWhatTime.getWtNumber(),
				evaWhatTime.getWtEnd());
		try {
			jobService.pause(addJobInfo);
		} catch (Exception e) {
			e.printStackTrace();
			throw new IllegalArgumentException("暂停任务失败");
		}
	}
}
